package main.controller.admin;

import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import main.RequestHelper;
import main.TimeHelper;
import main.database.*;
import main.GlobalConfig;
import org.bson.Document;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@Controller
public class FictionListPageController {
    @RequestMapping(value = "/fictionlist")
    public String fictionListPage(ModelMap modelMap, HttpServletRequest request) {
        boolean isAdmin = false;
        String uuid = RequestHelper.getUserUUIDFromRequest(request);
        if (uuid != null && AccountHelper.isAdminFromUUID(uuid)) {
            isAdmin = true;
        }
        String account = AccountHelper.getAccountInfoFromUUID(uuid);
        boolean isLogin = AccountHelper.isExistFromUUID(uuid);

        modelMap.put("isLogin", isLogin);
        if (isAdmin) {
            List<String> titleList = new ArrayList<>();
            titleList.add("书名");
            titleList.add("类型");
            titleList.add("作者");
            titleList.add("评分");
            titleList.add("加入日期");

            MongoCollection<Document> collection = DatabaseMan.Instance().GetCollection(GlobalConfig.collectionNameOfArticle);
            FindIterable<Document> documents = collection.find();
            List<List> parentList = new ArrayList<>();
            for (Document doc : documents) {
                List<String> childList = new ArrayList<>();

                String cid = doc.getObjectId("_id").toString();
                String title = (String) doc.get("title");
                String rootcatlog = (String) doc.get("rootcatlog");
                String authorId = (String) doc.get("author");
                String author = AuthorHelper.getAuthorNameFromId(authorId);
                double dScore = (double) doc.get("score");
                String score = ScoreHelper.getFormattedScore(dScore);
                String createTime = (String) doc.get("createtime");

                childList.add(cid);
                childList.add(title);
                childList.add(rootcatlog);
                childList.add(author);
                childList.add(score);
                childList.add(createTime);

                parentList.add(childList);
            }

            long unread = NotifyHelper.countUnreadNotify(uuid);
            modelMap.put("titleList", titleList);
            modelMap.put("contentList", parentList);
            modelMap.put("userName", account);
            modelMap.put("unread", unread);
            modelMap.put("year2year", TimeHelper.getFormattedYear2Year());
            return "admin/fictionListPage";
        }
        else {
            return "/toppage";
        }
    }
}

